package http_proxy_middleware

import (
	"fmt"

	"gin-gateway/middleware"
	"gin-gateway/core/utils"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// HTTPJwtFlowLimitMiddleware jwt 流限制
func HTTPJwtFlowLimitMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		appInfo := GetApp(c)

		if appInfo.Qps > 0 {
			clientIpLimiter, err := utils.FlowLimitManager.GetLimiter(utils.FlowAppPrefix+appInfo.AppID+"_"+c.ClientIP(), float64(appInfo.Qps))
			if err != nil {
				middleware.ResponseError(c, 5001, err)
				c.Abort()
				return
			}
			if !clientIpLimiter.Allow() {
				middleware.ResponseError(c, 5002, errors.New(fmt.Sprintf("%v flow limit %v", c.ClientIP(), appInfo.Qps)))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
